//utf-8

//选择合约
function toAddContract(){
	
	var dialogStruct={
			'display':contextRootPath+'/tCMmContract/prepareExecute/toSelectContract',
			'width':800,
			'height':600,
			'title':'选择合约',
			'isIframe':'false',
			'buttons':[
			           {'text':'确定','action':doAddFromContractSure,'isClose':true},
			  		   {'text':'关闭','isClose':true}
			]
		};
		
		var dialogAdd =jyDialog(dialogStruct).open();

	
}

//确认合约
function doAddFromContractSure(){
	var contractCode = iframeSelectContract.iframeObj["table"].getSelectedObjs("contractCode");
	window.location = contextRootPath+'/transfereeSettle/prepareExecute/toBackTransfereeDealAdd?contractCode='+contractCode;
}

//双击合约
function doAddFromContract(contractCode){
	 window.location = contextRootPath+'/transfereeSettle/prepareExecute/toBackTransfereeDealAdd?contractCode='+contractCode;
}


function isShowContract(){
	$("#creditPackageColumn").show();
	searchCreditPackage();
}

//查询债权包隐藏标签
var selectOptions=[];
//查询债权包	
function searchCreditPackage(selectID,updatePackageValue,type){
	var valueCooperorgCode = $('#dtocooperorgCode').val();
	var valueContractCode = $('#dtocontractCode').val();
	var dataUrl = contextRootPath + '/cooperorgDeal/getPackageListByAll?cooperorgCode=' + valueCooperorgCode +'&contractCode='+valueContractCode;//+ "&pagType=" + cimsConstant.CREDIT_RESOURCE
	$('#creditPackage').html("<option id='selectValue' name='请选择' value='-1'>请选择</option>");
	$.ajax({
		url: dataUrl,
		type: 'get',
		dataType: 'json',
		data:'',
		error: function(result) {
			alert("请查看返回数据是否正确：" + result);
		},
		success: function(results) {
			var result=results.data;
			var j;
			var resultLength = result.length - 1;
			for (j = 0; j <= resultLength; j++) {
				$('#creditPackage').append("<option name='"+result[j].creditPackageName+"' value='"+result[j].billDate+"'>"+result[j].creditPackageName+"</option>");
				selectOptions.push(result[j].creditPackageName);
			}
			completePackage(selectOptions,selectID,updatePackageValue,type);
//			completePackage(selectOptions,selectID);
		}
	});

}

//选择债权包
function creditPackageOperation(obj){
	$("#redemptionDate").val("");
}

function getCreditPackage(){
	var dealPackage = $("#dealPackage").val();
	if(dealPackage==""){
		alert("请选择赎回包！");
	}else{
		initFnCreditDetailView();
	}
}

//债权包输入
function creditPackageOperationWrite(obj){
	
	var valueWrite = obj.value;
	$("#creditPackage option[name='"+valueWrite+"']").attr("selected","true");
	var value = $("#creditPackage option[name='"+valueWrite+"']").val();
	
	
	if(-1==value){
		var textValue = $("#creditPackage").find("option:selected").val();
		$("#creditPackage option[value="+textValue+"]").attr("selected","true");
		$('#statementDate').removeAttr("disabled");
		$("#creditPackageWrite").val("");
		
	}else if (value=="1"){
		var textValue = $("#creditPackage").find("option:selected").val();
		$("#statementDate option[value="+textValue+"]").attr("selected","true");
		$('#statementDate').attr("disabled","disabled");

	}else if(value=="16"){
		var textValue = $("#creditPackage").find("option:selected").val();
		$("#statementDate option[value="+textValue+"]").attr("selected","true");
		$('#statementDate').attr("disabled","disabled");
	}else{
		$('#statementDate').removeAttr("disabled");
	}
	
}

/**
 * 债权受让导入
 */
function transfereeImport(){
	var creditPackageWrite = $('#dealPackage').val(); //包
	if(null==creditPackageWrite||""==creditPackageWrite){
		alert("请选择或者输入包名！");
		return ;
	}
	var dtocontractCode = $('#dtocontractCode').val();  //合约编号
	var dealType = $("#dealType").val();//业务类型：受让
	var className = "com.jy.modules.cims.data.dto.CreditDetailDto"; //实体
	//var creditPackageWrite = $('#creditPackageWrite').val();
	/**
	 * 调用公用的导入方法
	 */
	publicImportMothed(dtocontractCode,dealType,cimsConstant.SESSION_IMPORT_DATA_PATH,className,creditPackageWrite,"callback();");
}

/**
 *回调方法：假回调
 */
function callback(){
	var importDataId = $("#importDataId").val();//excel解析数据的数据KEY
	var dealCode = $('#dealCode').val(); //交易流水号
	var valueCooperorgCode = $('#dtocooperorgCode').val();//转让机构编号
	var creditPackage = $('#dealPackage').val(); //包
	var dtocontractCode = $('#dtocontractCode').val();  //合约编号
	var dtoagreementCode = $('#dtoagreementCode').val(); //协议编号
	var redemptionDate = $('#redemptionDate').val(); //协议编号
	var flag = "";
	$.ajax({
        type:"post",
        dataType: 'json',
        async:false,
        url:contextRootPath+"/transfereeSettle/doTransfereeDeal",
        data:{
         "transfereeCode":"JY",//受让编号：捷越
         "transferorCode":valueCooperorgCode, //转让编号
       	 "packageNum":creditPackage,
       	 "contractCode":dtocontractCode,
       	 "agreementCode":dtoagreementCode,
       	 "dealCode":dealCode,
       	 "dataType":"01",
       	 "dataId":importDataId,
       	 "redeemDate":redemptionDate,
        },
        success:function(msg){
        	if(msg.status=="ok"){
        		
        	
	        	var dto = msg.data;
	        	if(dto!=null){
	            	$('#dealCode').val(dto.dealCode);
	            	//加载债权信息
	            	initFnCreditDetailView();
	    			$("#creditDetailTable").show();
	        	}
	        	flag = "处理成功";
	        	/*$("#importContract").remove();//导入合约隐藏
	        	$("#importButton").remove();//导入按钮合约隐藏
	        	$("#creditPackage").attr('disabled',true);//选择包只读
	        	$("#creditPackageWrite").attr('disabled',true);//选择包只读
	        	$("#statementDate").attr('disabled',true);//账单日不能再选
*/        	}else {
        		flag = "处理失败:"+msg.msg;
        	}
        	
        }
    });
	return flag;
}


/**
 * 完成按钮操作-生成还款计划
 */
function saveDeal(){
	var dealCode = $('#dealCode').val();
	var dataUrl =contextRootPath + "/creditDealController/saveTransFereeDeal";
	  art.dialog({title: '询问', content: '"确认完成，生成还款计划？', ok: function () {
		  $.ajax({
				url: dataUrl,
				type: 'post',
				dataType: 'json',
				data:{"dealCode":dealCode},
				success: function(msg) {
					if(msg.status=="ok"){
						art.dialog({title: '处理结果', content: msg.msg, ok: function () {return true; }, lock:true, background:'#600', opacity: 0.10});
						$("#isDeleteAndIsExport").val("true");
						$("#saveDeal").hide();
						$("#dealPackage").attr("disabled","disabled");
						var winObj = parent.tabs.getTabWinByTitle("受让交易");
						if(winObj)
							winObj.location.reload();
						//parent.tabs.close();
					}else{
						art.dialog({title: '处理结果', content: msg.msg, ok: function () {return true; }, lock:true, background:'#600', opacity: 0.10});
					}
				}
			});
	  }, cancel: true, icon: 'question', lock:true, background:'#600', opacity: 0.10});
}

/**
 * 完成按钮操作-验证
 */
function saveCreditDeal_bak(){
	var dealCode = $('#dealCode').val();
	
	if(null==dealCode ||""==dealCode){
		alert("请导入债权！");
		return;
	}
	var dataUrl =contextRootPath + "/tCMmCreditDealDetail/queryListTCMmCreditDealDetail?dealStreamCode=" + dealCode;
	$.ajax({
		url: dataUrl,
		type: 'get',
		dataType: 'json',
		data:'',
		success: function(results) {
			var result=results.data;
			var resultLength = result.length;
			if(resultLength<=0){
				alert("该交易下没有债权！");
			}else {
				saveDeal();
			}
		}
	});
}


/**
 * 关闭按钮操作
 */
function closeFather(){
	var winObj = parent.tabs.getTabWinByTitle("受让交易");
	if(null==winObj){
		parent.tabs.close();
	}else{
		winObj.location.reload();
		parent.tabs.close();
	}
	
}



//债权价值合计
function CreditValueSum(){
	var dealCode = $("#dealCode").val();
	var dataUrl =contextRootPath + "/cooperorgDeal/getDealDetailByCreditSumTotal";	
	$.ajax({
		url: dataUrl,
		type: 'post',
		dataType: 'json',
		data:{"dealCode":dealCode},
		error: function(result) {
			
			alert("请查看返回数据是否正确：" + result);
		},
		success: function(results) {
			var obj = results.data;
			$("#detialNumber").val(obj.detialNumber);
			$("#sumCreditorValue").val(obj.sumCreditorValue);
		}
	});
}



//返回合约
function returnContract(contractCode){
	
	var dataUrl =contextRootPath + "/tCMmContract/returnContract";	
	$.ajax({
		url: dataUrl,
		type: 'post',
		dataType: 'json',
		data:{"contractCode":contractCode},
		error: function(result) {
			
			alert("请查看返回数据是否正确：" + result);
		},
		success: function(results) {
			var obj = results.data;
			if(obj[0].length<0){
				return;
			}
			var creditorAffirmRule = obj[0].cdto.creditorAffirmRule;
			var dealType = obj[0].cdto.dealType;
			if(creditorAffirmRule=='01'){
				$("#dtocreditorAffirmRule").attr("value","发起方");
			}else if(creditorAffirmRule=='02'){
				$("#dtocreditorAffirmRule").attr("value","接收方");
			}
			$("#creditorAffirmRule").attr("value",dealType);
		}
	});
}

function selectStyle(){
	var cooperorgCode = $('#dtocooperorgCode').val();
	var contractCode = $('#dtocontractCode').val();
	if(cooperorgCode!="" && null !=cooperorgCode){
		$("select[name=cooperorgCode]").find("option[value='" + cooperorgCode + "']").attr("selected",true);
		$("select[name=contractCode]").find("option[value='" + contractCode + "']").attr("selected",true);
	}
}

function isShowCooperorg(){
	$("#creditRestrainTitle").show();
	$("#creditRestrainTitleValue").show();
	$("#creditOperation").show();
	$("#creditDetailOperation").show();
}




//试算
function settleCreditDeal(){
	var dealCode = $('#dealCode').val();
	
	if(null==dealCode || ""==dealCode){
		alert("请先导入债权确认信息！");
		return;
	}
	
	if(confirm("请确认导入的债权信息!")){
		var dataUrl =contextRootPath + "/settle/testSettleCooperorgDeal";
		$.ajax({
			url: dataUrl,
			type: 'post',
			dataType: 'json',
			data:{"dealCode":dealCode},
			success: function(results) {
				
			}
		});
	}
}




/*function packageDay(url){
	
	 $.ajax({
         type:"get",
         dataType : "json",
         url:url,
         success:function(msg){
         	
        	 
         	
         	
         }
     });
}*/


function sumSelectValue(){
	var thisMakeCreditorValues = iframeCredit.iframeObj["table"].getSelectedObjs("thisMakeCreditorValue");
	var thisMakeCreditorValueLength = thisMakeCreditorValues.length;
	var i;
	var selectedCreditValue = $("#sumCreditorValue").val();
	if(selectedCreditValue==null||selectedCreditValue==""){
		selectedCreditValue = "0";
	}
	selectedCreditValue  = parseFloat(selectedCreditValue);
	var thisMakeCreditorValue;
	if(thisMakeCreditorValueLength>0){
		for(i=0;i<thisMakeCreditorValueLength;i++){
			thisMakeCreditorValue =parseFloat(thisMakeCreditorValues[i]);
			selectedCreditValue  += thisMakeCreditorValue;
		}
		selectedCreditValue = selectedCreditValue.toFixed(2);
		$("#selectedCreditValue").val(selectedCreditValue);
	}else{
		var sumCreditorValue = $("#sumCreditorValue").val();
		if(sumCreditorValue==null||sumCreditorValue==""){
				$("#selectedCreditValue").val(0);
		}else{
				$("#selectedCreditValue").val(sumCreditorValue);
		}
	}
	
}


$(document).ready(function(){
	//给导入按钮赋方法
	$("#importButton").click(function(){
		transfereeImport();
	});
	$('#creditorAffirmRule').attr("disabled","disabled");
});


//保存交易流水
function saveCreditDeal(isComeExport){
	var obj  = $('#cooperorgCode').length;
	var valueCooperorgCode;
	if(obj>0){
		valueCooperorgCode = $('#cooperorgCode').val();
	}else {
		valueCooperorgCode = $('#dtocooperorgCode').val();
	}
	
	var obj  = $('#contractCode').length;
	var valueContractCode;
	if(obj>0){
		valueContractCode = $('#contractCode').val();
	}else {
		valueContractCode = $('#dtocontractCode').val();
	}
	var creditPackageName = $('#dealPackage').val();
	var dealCode = $('#dealCode').val();
	var id = $('#idValue').val();
	var redemptionDate = $('#redemptionDate').val();
	var dtoagreementCode = $('#dtoagreementCode').val();
	if(valueContractCode!=null && valueContractCode!=""){
		if(null==creditPackageName ||""==creditPackageName){
			alert("请选择或者填写包名！");
			return;
		}
		if(null==redemptionDate || ""==redemptionDate){
			alert("请选择赎回日期！");
			return;
		}
	}
	
	if(isComeExport==true?true:confirm("确认保存！")){
		var dataUrl =contextRootPath + "/transfereeSettle/saveTransferRedemp";
		
		var param = {"cooperorgCode":valueCooperorgCode,
				  "contractCode":valueContractCode,
				  "creditPackageName":creditPackageName,
				  "redemptionDate":redemptionDate,
				  "agreementCode":dtoagreementCode,
				  "dealCode":dealCode,
				  "id":id};
		
		jyAjax(
				dataUrl,
				param,
				function(results){
					var v_status = results.status;
					if(v_status.indexOf('ok') >-1){
						var obj=results.data;
						$("#idValue").val(obj.id);
						$("#dealCode").val(obj.dealCode);
						$("#IsExport").val("true");
						$("#dealPackage").attr("disabled","disabled");
						$("#redemptionDate").attr("disabled","disabled");
						var winObj = parent.tabs.getTabWinByTitle("受让赎回");
						if(winObj)
							winObj.location.reload();
						//parent.tabs.close();
						if(isComeExport){
							sureExport();
						}else{
							alert("保存成功！");
						}
	    		
				}
		});
		
		
		/*$.ajax({
			url: dataUrl,
			type: 'post',
			dataType: 'json',
			data:{"cooperorgCode":valueCooperorgCode,
				  "contractCode":valueContractCode,
				  "creditPackageName":creditPackageName,
				  "redemptionDate":redemptionDate,
				  "agreementCode":dtoagreementCode,
				  "dealCode":dealCode,
				  "id":id},
			success: function(results) {
				var obj = results.data;
				$("#idValue").val(obj.id);
				$("#dealCode").val(obj.dealCode);
				$("#isDeleteAndIsExport").val("true");
				$("#dealPackage").attr("disabled","disabled");
				$("#redemptionDate").attr("disabled","disabled");
				var winObj = parent.tabs.getTabWinByTitle("受让赎回");
				if(winObj)
					winObj.location.reload();
				//parent.tabs.close();
				if(isComeExport){
					sureExport();
				}else{
					alert("保存成功！");
				}
				
			}
		});*/
	}
	
}

//确认赎回
function confirmCreditDeal(){
	var obj  = $('#cooperorgCode').length;
	var valueCooperorgCode;
	if(obj>0){
		valueCooperorgCode = $('#cooperorgCode').val();
	}else {
		valueCooperorgCode = $('#dtocooperorgCode').val();
	}
	var valueContractCode;
	if(obj>0){
		valueContractCode = $('#contractCode').val();
	}else {
		valueContractCode = $('#dtocontractCode').val();
	}
	var dealCode = $('#dealCode').val();
	//var redemptionDate = $('#redemptionDate').val();
	if(dealCode==""){
		alert("请先保存交易！");
		return ;
	}
	
	
	var dataUrl =contextRootPath + "/transfereeSettle/confirmTransferRedemp";
	 art.dialog({title: '询问', content: '确认赎回？', ok: function () {
		  $.ajax({
				url: dataUrl,
				type: 'post',
				dataType: 'json',
				data:{"cooperorgCode":valueCooperorgCode,
					  //"redemptionDate":redemptionDate,
					  "contractCode":valueContractCode,
					  "dealCode":dealCode},
				success: function(msg) {
					if(msg.status=="ok"){
						art.dialog({content: msg.msg, ok: function () {return true; }, lock:true, background:'#600', opacity: 0.10, icon: 'succeed',
							init: function () {
						    	var that = this, i = 10;
						        var fn = function () {
						            that.title(i + ' 秒后自动关闭');
						            !i && that.close();
						            i --;
						        };
						        timer = setInterval(fn, 1000);
						        fn();
						    },
						    close: function () {
						    	clearInterval(timer);
						    }
                       });
						var winObj = parent.tabs.getTabWinByTitle("受让赎回");
						if(winObj)
							winObj.location.reload();
						//parent.tabs.close();
					}else{
						art.dialog({content: msg.msg, ok: function () {return true; }, lock:true, background:'#600', opacity: 0.10,  icon: 'error',
							init: function () {
						    	var that = this, i = 10;
						        var fn = function () {
						            that.title(i + ' 秒后自动关闭');
						            !i && that.close();
						            i --;
						        };
						        timer = setInterval(fn, 1000);
						        fn();
						    },
						    close: function () {
						    	clearInterval(timer);
						    }
                       });
					}
					
					
				}
			});
	  }, cancel: true, icon: 'question', lock:true, background:'#600', opacity: 0.10});
	 
	 /*
	if(confirm("确认赎回！")){
		var dataUrl =contextRootPath + "/transfereeSettle/confirmTransferRedemp";
		$.ajax({
			url: dataUrl,
			type: 'post',
			dataType: 'json',
			data:{"cooperorgCode":valueCooperorgCode,
				  "redemptionDate":redemptionDate,
				  "contractCode":valueContractCode,
				  "dealCode":dealCode},
			success: function(msg) {
				if(msg.status=="ok"){
		        	var dto = msg.data;
		        	alert("赎回成功");
	        	}else {
	        		alert("赎回失败:"+msg.msg);
	        	}
				
				var winObj = parent.tabs.getTabWinByTitle("受让赎回");
				if(winObj)
					winObj.location.reload();
				//parent.tabs.close();
				alert("赎回成功！");
			}
		});
	}*/
	
}

//导出受让赎回
function exportTransfereeRedemption(){
	var IsExport = $("#IsExport").val();
	if(IsExport){
		sureExport();
	}else{
		saveCreditDeal(true);
	}
	
}
